import {StyleSheet, Text, TouchableOpacity, View, TextInput, Image} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import FormTitle from "@/components/FormTitle";
import NoData from "@/components/NoData";
import CopyWriting from "@/components/CopyWriting";
import {Video} from 'expo-av';
import {router, useLocalSearchParams} from "expo-router";
import {Toast, Flex} from "@ant-design/react-native";
import {useDispatch, useSelector} from "react-redux";
import {set_videoList} from "@/store/reducer/videoPublish/videoPublishSlice";

import {
  useGetTitleMutation,
  useGetAccountAllMutation
} from "@/store/api/videoPublish/videoPublishApi";

type Props = {}

const batch = (props: Props) => {
  const [listParams, setListParams] = useState({
    pageNo: 1,
    pageSize: 20,
    content: '',
  })
  const [titleType,setTitleType] = useState<any>('')
  const [copyWritingOpen, setCopyWritingOpen] = useState(false)
  const [videoList,setVideoList] = useState<any>([])
  const [accountList,setAccountList] = useState<any>([])
  const [accountOpen,setAccountOpen] = useState(false)
  const [isBatch, setIsBatch] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [ksIndex,setKsIndex] = useState(0)
  
  const [getAccountAllFun] = useGetAccountAllMutation()
  const [getTitleFun] = useGetTitleMutation()

  const dispatch = useDispatch()
  const {type} = useLocalSearchParams()

  let p = useSelector(state => state.videoPublish.videoList)

  useEffect(() => {
    let arr = JSON.parse(JSON.stringify(p))

    arr.forEach((val: any) => {
      val.isShow = false
    });

    setVideoList(arr)
    setTitleType(type)
  },[p, type])

  useEffect(() => {
    getAccountAllList();
  }, []);

  //获取发布账号列表
  const getAccountAllList = () => {
    getAccountAllFun({}).then(res => {
      let list = res.data?.result.filter((val:any) => val.sourcePlatform == 'kuaishou') || []
      setAccountList(list)
    })
  }

  //选择文案
  const handleCheckCopy = (item:any) => {
    let arr = JSON.parse(JSON.stringify(videoList))
    arr[ksIndex].title = item
    setVideoList(arr)
  }

  const handleCheckVideo = (index:any) => {
    let arr = JSON.parse(JSON.stringify(videoList))
    arr[index].checked = !arr[index].checked
    setVideoList(arr)
  }

  //选择发布账号
  const handleCheckAccount = (index:any) => {
    let arr = JSON.parse(JSON.stringify(accountList))
    arr[index].checked = !arr[index].checked
    setAccountList(arr)
  }
  //提交发布账号
  const handleSubmitAccount = () => {
    if(accountList.filter((val:any) => val.checked).length == 0) return

    if(!isBatch){
      let arr = JSON.parse(JSON.stringify(videoList))
      arr[ksIndex].accountArr = accountList.filter((val:any) => val.checked)
      setVideoList(arr)
      setAccountOpen(false)
    }else{
      let arr = JSON.parse(JSON.stringify(videoList))

      for(let i in arr){
        if(arr[i].checked){
          arr[i].accountArr = accountList.filter((val:any) => val.checked)
          arr[i].checked = false
        }
      }

      setVideoList(arr)
      setAccountOpen(false)
      dispatch(set_videoList(arr))
      router.back()
    }
  }

  //删除发布账号
  const handleDeleteAccount = (item:any, index:any) => {
    let arr = JSON.parse(JSON.stringify(videoList)); 
    arr[ksIndex].accountArr.splice(index, 1); 
    setVideoList(arr)

    let arr1 = JSON.parse(JSON.stringify(accountList)); 
    let index1 = arr1.findIndex((val:any) => val.id == item.id)
    arr1[index1].checked = false
    setAccountList(arr1)
  }

  //AI编写
  const handleAiTitle = async(path:any, index:any) => {
    Toast.config({ duration: 0})
    let loading = Toast.loading('AI编写中')

    getTitleFun({videoPath: path}).then(res => {
      if(res.data.code === 200){
        Toast.remove(loading)
        Toast.config({ duration: 2})

        let arr = JSON.parse(JSON.stringify(videoList))
        arr[index].title = res.data.result[0]
        setVideoList(arr)
      }else{
        Toast.remove(loading)
        Toast.config({ duration: 2})
        Toast.info(res.data.message)
      }
    })
  }

  const handleSubmit = async() => {
    if(videoList.filter((val:any) => val.checked).length == 0) return

    let arr = JSON.parse(JSON.stringify(videoList))

    if(titleType == 'write'){
      Toast.config({ duration: 0})
      let loading = Toast.loading('AI编写中')

      for(let i in arr){
        if(arr[i].checked){
          await getTitleFun({videoPath: arr[i].filePath}).then(res => {
            if(res.data.code === 200){
              arr[i].title = res.data.result[0]
              arr[i].checked = false

              Toast.remove(loading)
              Toast.config({ duration: 2})
            }else{
              Toast.remove(loading)
              Toast.config({ duration: 2})
              Toast.info(res.data.message)
            }
          })
        }
      }

      setVideoList(arr)
      dispatch(set_videoList(arr))
      router.back()
    }else if(titleType == 'account'){
      setIsBatch(true)
      setAccountOpen(true)
    }else if(titleType == 'delete'){
      setDeleteOpen(true)
    }
  }

  //显示更多设置
  const handleCheckShow = (index) => {
    let arr = JSON.parse(JSON.stringify(videoList))
    arr[index].isShow = true
    setVideoList(arr)
  }

  //批量删除视频
  const handleVideoDelete = () => {
    let arr = videoList.filter((val:any) => !val.checked)

    setVideoList(arr)
    dispatch(set_videoList(arr))
    router.back()
  }

  return (
    <PageScrollView
      isTransparentTab
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={titleType == 'write' ? 'AI编写标题/发布语' : titleType == 'account' ? '批量设置发布账号' : titleType == 'pubTime' ? '批量设置发布时间' : '批量删除'}
        />
      }
      pageBottom={
        <Flex justify='between' align='center' style={{height: 56, backgroundColor: '#FFF', paddingHorizontal: 16}}>
          <Text style={{color: 'rgba(0, 0, 0, 0.3)'}}>已选{ videoList.filter((val:any) => val.checked).length }个</Text>

          <FcButton
            onClick={() => handleSubmit()}
            type='BjJB'
            colors={videoList.filter((val:any) => val.checked).length > 0 ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
            style={{width: 120, height: 40, justifyContent: 'center'}}
            itemStyle={{borderRadius: 8, fontSize: 15}}
            textName={titleType == 'write' ? 'AI编写' : titleType == 'account' ? '设置发布账号' : titleType == 'pubTime' ? '设置发布时间' : '删除'}
          />
        </Flex>
      }
    >
      <View>
        {
          videoList.map((item:any, index:any) => (
            <View key={index} style={{backgroundColor: '#FFF', padding: 14, borderRadius: 8, marginTop: 10}}>
              <View>
                <View style={{height: 200, display: 'flex', flexDirection: 'row', position: 'relative'}}>
                  <View style={{width: '35%', height: '100%', backgroundColor: '#000', borderRadius: 8}}>
                    <Image style={{width: '100%', height: '100%', borderRadius: 8}} resizeMode={'cover'} source={{uri: item.temporaryCover}}></Image>
                  </View>
                  <View style={{flex: 1, marginLeft: 10, display: 'flex', flexDirection: 'column'}}>
                    <Flex justify='between'>
                      <Text>标题/发布语</Text>
                      <TouchableOpacity style={[styles.select_icon, {marginRight: 0}, item.checked && styles.select_active]} onPress={() => {handleCheckVideo(index)}}>
                        {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                      </TouchableOpacity>
                    </Flex>
    
                    <TextInput
                      style={[styles.content_input, {flex: 1}]}
                      multiline={true}
                      value={item?.title}
                      placeholderTextColor={'rgba(0, 0, 0, 0.3)'}
                      placeholder={'请输入'}
                      onChangeText={(val) => {let arr = JSON.parse(JSON.stringify(videoList)); arr[index].title = val; setVideoList(arr)}}
                    />
                    <Flex style={{position: 'absolute', bottom: 8, right: 10}}>
                      <TouchableOpacity style={[styles.btn, {marginRight: 5}]} onPress={()=> {setCopyWritingOpen(true), setKsIndex(index)}}>
                        <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: '#2856FF'}}>&#xe655;</Text>
                        <Text style={{color: '#2856FF', fontSize: 12, marginLeft: 3}}>导入发布语</Text>
                      </TouchableOpacity>
    
                      <TouchableOpacity style={styles.btn} onPress={()=> handleAiTitle(item.filePath, index)}>
                        <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: '#2856FF'}}>&#xe63d;</Text>
                        <Text style={{color: '#2856FF', fontSize: 12, marginLeft: 3}}>AI编写</Text>
                      </TouchableOpacity>
                    </Flex>
                  </View>
                </View>

                {
                  item.isShow ?
                  <View>
                    <View style={{borderTopWidth: 0.5, borderColor: 'rgba(0, 0, 0, 0.1)', marginTop: 16}}></View>

                    <FormTitle title='选择发布账号'/>
                    <TouchableOpacity onPress={() => {setKsIndex(index); setIsBatch(false); setAccountOpen(true);}}>
                      <View style={styles.item_wrap}>
                        {
                          item?.accountArr?.length > 0 ?
                            <Flex wrap='wrap' style={{flex: 1}}>
                            {
                              item?.accountArr?.map((childrenItem:any, childrenIndex:any) => (
                                <Flex key={childrenIndex} style={{paddingHorizontal: 8, height: 24, borderRadius: 4, backgroundColor: '#FFF', marginRight: 10, marginVertical: 5}}>
                                  <Image style={{width: 20,height: 20, borderRadius: '50%'}} source={{uri: childrenItem.avatar}} resizeMode={'contain'}></Image>
                                  <Text style={{fontSize: 12, marginLeft: 3, marginRight: 10}}>{childrenItem.nickname}</Text>
                                  <TouchableOpacity onPress={()=> handleDeleteAccount(childrenItem, childrenIndex)}>
                                    <Text style={{fontFamily: 'FcIconFont',fontSize: 16,color: 'rgba(0, 0, 0, 0.5)'}}>&#xe667;</Text>
                                  </TouchableOpacity>
                                </Flex>
                              ))
                            }
                          </Flex>
                          :
                          <Text style={[styles.item_hint]}>请选择</Text>
                        }
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe609;</Text>
                      </View>
                    </TouchableOpacity>

                    <FormTitle style={{marginTop: 8}} title='设置发布时间'/>
                    <TouchableOpacity onPress={() => {}}>
                      <View style={styles.item_wrap}>
                        <Text style={[false ? styles.item_label : styles.item_hint]}>{false || '立即发布'}</Text>
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#79797A'}}>&#xe64c;</Text>
                      </View>
                    </TouchableOpacity>
                  </View>
                  :
                  <TouchableOpacity onPress={() => handleCheckShow(index)}>
                    <Flex justify='center' style={{marginTop: 12}}>
                      <Text style={{fontSize: 12, color: '#7985A8', marginRight: 5}}>显示更多设置</Text>
                      <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#7985A8'}}>&#xe600;</Text>
                    </Flex>
                  </TouchableOpacity>
                }
              </View>
            </View>
          ))
        }

        {/* 选择文案 */}
        <CopyWriting
          isOpen={copyWritingOpen}
          onClose={() => setCopyWritingOpen(false)}
          onConfirm={(item:any) => handleCheckCopy(item)}
        ></CopyWriting>

        {/* 发布账号弹窗 */}
        <FcModal
          isOpen={accountOpen}
          onFcModalClose={() => setAccountOpen(false)}
          titleText='发布账号'
          titleBottomBorderWidth={0}
          bottom={
            <View style={styles.modal_bottom}>
              <Text style={{color: 'rgba(0, 0, 0, 0.3)'}}>已选{ accountList.filter((val:any) => val.checked).length }个</Text>

              <FcButton
                onClick={() => handleSubmitAccount()}
                type='BjJB'
                colors={accountList.filter((val:any) => val.checked).length > 0 ? ['#6989FF', '#C65EFD'] : ['rgba(105,137,255,0.4)', 'rgba(198,94,253,0.4)']}
                style={{width: 120, height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='确定'
                borderWidth={1}
              />
            </View>
          }
        >
          <View style={{backgroundColor: '#F1F2F4', paddingHorizontal: 16, paddingBottom: 10, flex: 1}}>
            {
              accountList.length == 0 ?
              <Flex justify='center' style={{flex: 1}}>
                <NoData hintText='暂无数据'/>
              </Flex>
              :
              accountList.map((item:any, index:any) => (
                <Flex key={index} style={[styles.account_item]}>
                  <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active]} onPress={() => {handleCheckAccount(index)}}>
                    {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                  </TouchableOpacity>
                  <Image style={{width: 32,height: 32, borderRadius: '50%', marginRight: 10}} source={{uri: item.avatar}} resizeMode={'contain'}></Image>
                  <Text>{ item.nickname }</Text>
                </Flex>
              ))
            }
          </View>
        </FcModal>

        {/* 删除弹窗 */}
        <FcModal
          isOpen={deleteOpen}
          transparent
          closeShow={false}
          animationType='fade'
          onFcModalClose={() => setDeleteOpen(false)}
          style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleText={'确认要删除吗？'}
          titleBottomBorderWidth={0}
          footer={[
            {
              text: '取消',
              onPress: () => setDeleteOpen(false),
              style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
            },
            {
              text: '确认',
              onPress: () => handleVideoDelete(),
              style: { color: '#2856FF',fontSize: 17 },
            },
          ]}
        >
          <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前视频将被删除哦~</Text>
        </FcModal>
      </View>
    </PageScrollView>
  )
}

export default batch

const styles = StyleSheet.create({
  upload_video: {
    width: '100%',
    height: 56,
    borderRadius: 8,
    borderWidth: 1,
    borderStyle: 'dashed',
    borderColor: '#0256FF',
    backgroundColor: '#FFF'
  },
  content_input: {
    backgroundColor: '#F1F2F4',
    color: 'rgba(0,0,0,0.9)',
    lineHeight: 26,
    paddingBottom: 40,
    paddingHorizontal: 12,
    borderRadius: 8,
    marginTop: 5,
    textAlignVertical: 'top',
  },
  btn: {
    paddingHorizontal: 8,
    height: 28,
    borderRadius: 6,
    backgroundColor: '#FFF',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  item_wrap: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: 'space-between',
    minHeight: 56,
    paddingHorizontal: 12,
    backgroundColor: '#F1F2F4',
    borderRadius: 8,
    paddingVertical: 10,
  },
  item_label: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)'
  },
  item_hint: {
    fontSize: 17,
    color: 'rgba(0,0,0,0.3)'
  },
  account_item: {
    height: 72,
    borderRadius: 8,
    marginTop: 10,
    paddingHorizontal: 12,
    backgroundColor: '#FFF',
  },
  select_icon: {
    width: 20,
    height: 20,
    borderRadius: '50%',
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.5)',
    marginRight: 12,
  },
  select_active: {
    borderColor: '#2856FF',
    backgroundColor: '#2856FF',
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: "center"
  },
  modal_bottom: {
    height: 76,
    display: 'flex',
    flexDirection: "row",
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
  },
  batch_item: {
    display: 'flex', 
    flexDirection: 'row', 
    alignItems: 'center', 
    height: 40
  }
})